package com.eastmelon.blog.dao.impl;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;

import com.eastmelon.basic.model.Pager;
import com.eastmelon.basic.model.SystemContext;
import com.eastmelon.blog.dao.BaseDao;

public abstract class BaseDaoImpl<T> extends SqlSessionDaoSupport implements BaseDao<T>{
	@Autowired
	//mybatis-spring 1.0无需此方法；mybatis-spring1.2必须注入。
	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory){
		super.setSqlSessionFactory(sqlSessionFactory);
	}
	
	private String ns;		//命名空间
	public String getNs() {
		return ns;
	}
	public void setNs(String ns) {
		this.ns = ns;
	}

	public List<T> find(Map map) {
		List<T> oList = this.getSqlSession().selectList(ns + ".find", map);
		return oList;
	}
	public T get(Serializable id) {
		return this.getSqlSession().selectOne(ns + ".get", id);
	}

	public void save(T entity) {
		this.getSqlSession().insert(ns + ".save", entity);
	}

	public void update(T entity) {
		this.getSqlSession().update(ns + ".update", entity);
	}

	public void deleteById(Serializable id) {
		this.getSqlSession().delete(ns + ".deleteById", id);
	}

	public void deleteByIds(Serializable[] ids) {
		this.getSqlSession().delete(ns + ".deleteByIds", ids);
	}
	public Pager<T> findPage(){
		int pageSize=SystemContext.getPageSize();
		int pageOffset=SystemContext.getPageOffset();
		Pager<T> pager=new Pager<T>();
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("pageSize", pageSize);
		params.put("pageOffset", pageOffset);
		List<T> datas=this.getSqlSession().selectList(ns+".findPage",params);
		int total=this.getSqlSession().selectOne(ns+".getTotal");
		pager.setDatas(datas);
		pager.setOffset(pageOffset);
		pager.setSize(pageSize);
		pager.setTotal(total);
		return pager;
	}
}
